package com.fzh.wangxiao.utils;


import org.apache.commons.lang3.RandomUtils;

public class ShortUUID {

    private static final char[] digits = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
    private static final long ERA_TIME = 1573808400000L;
    // UUID一次轮回的指数. 12则为大概30年左右,11则为3年左右. 业务逻辑短时间内唯一即可
    private static final int TIME_LOOP_INDEX = 12;
    private static final int COLLISION_INDEX = 99999999;

    public static String randomUUID() {
        long passTime = System.currentTimeMillis() - ERA_TIME;

        // 反转后右补0
        StringBuilder stringBuilder = new StringBuilder(String.valueOf(passTime)).reverse();
        while (stringBuilder.length() < TIME_LOOP_INDEX) {
            stringBuilder.append('0');
        }
        long l = Long.parseLong(stringBuilder.substring(0, TIME_LOOP_INDEX));

        return toString(l, digits.length) + toString(RandomUtils.nextInt(0,COLLISION_INDEX), digits.length);
    }

    /**
     * 将10进制转换成任意进制,
     * 照着Long原生的进制转换写的,原生最大支持到32进制,这里支持到62进制,理论上可以扩展digits数组实现更高
     */
    public static String toString(long i, int radix) {
        if (radix < 2 || radix > digits.length) {
            radix = 10;
        }
        if (radix <= 32) {
            return Long.toString(i, radix);
        }

        final int size = 65;
        int charPos = 64;

        char[] buf = new char[size];
        boolean negative = (i < 0);

        if (!negative) {
            i = -i;
        }

        while (i <= -radix) {
            buf[charPos--] = digits[(int) (-(i % radix))];
            i = i / radix;
        }
        buf[charPos] = digits[(int) (-i)];

        if (negative) {
            buf[--charPos] = '-';
        }

        return new String(buf, charPos, (size - charPos)).toLowerCase();
    }


}